public without sharing class AccountTeamMemberHandler {
    

    //在客户小组新建的时候去 共享客户信用的权限 
	 //在客户小组删除的时候去 删除客户信用的权限
    public static void shareAccountCredit(List<AccountTeamMember> members,boolean isdel  ){

    	Set<Id>users = new Set<Id>();
    	Set<Id>accs  = new Set<Id>();
    	Map<String,String >userAccMap  = new Map<String,String>();

    	for (AccountTeamMember atm  :members ) {
    		if(atm.UserId != null ){
    			users.add(atm.UserId);
    		}
    		if(atm.AccountId != null ) accs.add(atm.AccountId);
    		userAccMap.put(atm.UserId,atm.AccountId);
    	}

    	if(users.isEmpty())return;
    	//查找 用户信息
    	Set<String> companys  = new Set<String>();
    	Map<String,String >userComMap = new Map<String,String >();
    	for(User u : [select Id ,SubCompany__c ,IsActive from User where Id in:users ]){
    		if(!u.IsActive){
    			continue;
    		}
    		companys.add(u.SubCompany__c);
    		userComMap.put(u.Id,u.SubCompany__c);

    		
    	}

    	//查找客户信用信息
    	Map<String,Set<Id>> acShareMap = new Map<String,Set<Id>> ();
    	for ( AccountCredit__c ac : [select Id ,Account__c,Company__c  from AccountCredit__c where Company__c in: companys and Account__c in: accs  ] ) {
    			//ac.Account__c = 
    			//ac.Company__c= '迈克生物股份有限公司'
    			for (String userId  : userComMap.keySet() ) {
    				
    				if(userComMap.get(userId) == ac.Company__c && userAccMap.get(userId) == ac.Account__c ){
    					Set<Id> us = acShareMap.containsKey(ac.Id) ?  acShareMap.get(ac.Id ): new Set<Id>();
    					us.add(userId);
    					acShareMap.put(ac.Id , us);
    				}
    			}

    	}	
    
       if(acShareMap.isEmpty())return;
    	//查找客户信用共享信息
       List<AccountCredit__Share> asdel = new  List<AccountCredit__Share> ();
    	for(AccountCredit__Share  acs:[select Id,UserOrGroupId ,ParentId,AccessLevel,RowCause from AccountCredit__Share where ParentId in:acShareMap.keySet() ] ){

    		if(acShareMap.containsKey(acs.ParentId) && acShareMap.get(acs.ParentId).contains(acs.UserOrGroupId) ){
    			acShareMap.get(acs.ParentId).remove(acs.UserOrGroupId);
    			asdel.add(acs);
    		}

    	}

    	if(isdel ){
    		if(!asdel.isEmpty())delete asdel;
    		return;
    	}
    	List<AccountCredit__Share> acsL = new List<AccountCredit__Share>();

    	for (String acId  : acShareMap.keySet() ) {
    		for (String userId  :acShareMap.get(acId ) ) {
    			AccountCredit__Share acs = new AccountCredit__Share();
	    		acs.UserOrGroupId = userId ;
	    		acs.ParentId = acId ;
	    		acs.AccessLevel = 'Edit';

	    		acsL.add(acs);
    		}
    		
    	}

 		if(!acsL.isEmpty())insert acsL;


    }

   


}